package com.austin.smp.service.Impl;

import com.austin.smp.common.api.ResponseCode;
import com.austin.smp.common.api.ServerResponse;
import com.austin.smp.common.constant.Constant;
import com.austin.smp.common.util.DateTimeUtil;
import com.austin.smp.common.util.PropertiesUtil;
import com.austin.smp.converter.Product2ProductListVOConverter;
import com.austin.smp.dao.CategoryMapper;
import com.austin.smp.dao.ProductMapper;
import com.austin.smp.entity.Category;
import com.austin.smp.entity.Product;
import com.austin.smp.service.CategoryService;
import com.austin.smp.service.ProductService;
import com.austin.smp.vo.ProductDetailVO;
import com.austin.smp.vo.ProductListVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author austin
 * @since austin/6/15 13:19
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CategoryService categoryService;


    /**
     * 新增或者更新商品--后台
     *
     * @param product
     * @return
     */
    @Override
    public ServerResponse saveOrUpdateProduct(Product product) {
        if (product != null) {
            //将新增的商品的第一张图片设置为主图
            if (StringUtils.isNotBlank(product.getSubImages())) {
                String[] subPicArray = product.getSubImages().split(",");
                if (subPicArray.length > 0) {
                    product.setMainImage(subPicArray[0]);
                }
            }

            if (product.getId() != null) {
                int rowCount = productMapper.updateByPrimaryKey(product);
                if (rowCount > 0) {
                    return ServerResponse.createBySuccessMessage("更新商品成功");
                }
                return ServerResponse.createByErrorMessage("更新商品失败");
            } else {
                int rowCount = productMapper.insert(product);
                if (rowCount > 0) {
                    return ServerResponse.createBySuccessMessage("新增商品成功");
                }
                return ServerResponse.createByErrorMessage("新增商品失败");
            }
        }
        return ServerResponse.createByErrorMessage("新增或更新产品参数不正确");
    }

    /**
     * 获取返回ProductList对象 --前台、后台共用
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ServerResponse<PageInfo> getProductList(int pageNum, int pageSize) {
        List<Product> productList = productMapper.selectList();
        PageHelper.startPage(pageNum, pageSize);

        List<ProductListVO> productListVOList = Lists.newArrayList();
        for (Product productItem : productList) {
            //将对象Product组装成ProductListVO
            ProductListVO productListVO = Product2ProductListVOConverter.convert(productItem);
            productListVOList.add(productListVO);
        }

        PageInfo pageResult = new PageInfo(productList);
        pageResult.setList(productListVOList);
        return ServerResponse.createBySuccess(pageResult);
    }

    /**
     * 获取返回ProductDetailVO详情--前台使用
     *
     * @param productId
     * @return
     */
    @Override
    public ServerResponse<ProductDetailVO> getProductDetail(Integer productId) {
        if (productId == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null) {
            return ServerResponse.createByErrorMessage("商品已下架获已被删除");
        }
        //前台获取商品详情与后台不一致在与需要判断商品的状态是否是在线销售状态
        if (product.getStatus() != Constant.ProductStatusEnum.ON_SALE.getCode()) {
            return ServerResponse.createByErrorMessage("商品已下架获已被删除");
        }
        ProductDetailVO productDetailVO = assembleProductDetailVO(product);
        return ServerResponse.createBySuccess(productDetailVO);
    }


    /**
     * 产品搜索及动态排序List--前台使用产品搜索及动态排序List--前台使用
     *
     * @param keyword
     * @param categoryId
     * @param pageNum
     * @param pageSize
     * @param orderBy    排序参数：例如price_desc价格降序，price_asc价格升序
     * @return
     */
    @Override
    public ServerResponse<PageInfo> getProductByKeywordCategory(String keyword, Integer categoryId, int pageNum, int pageSize, String orderBy) {
        if (StringUtils.isBlank(keyword) && categoryId == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }

        List<Integer> categoryIdList = new ArrayList<Integer>();

        if (categoryId != null) {
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            if (category == null && StringUtils.isBlank(keyword)) {
                //如果分类和关键字为空，这时候应该返回空的结果集，而不是报错
                PageHelper.startPage(pageNum, pageSize);
                List<ProductListVO> productListVOList = Lists.newArrayList();
                PageInfo pageInfo = new PageInfo(productListVOList);
                return ServerResponse.createBySuccess(pageInfo);
            }
            //当传的是大的分类Id，也就是父类类目id这时候就需要找到响相应的子分类，调用CateService的selectCategoryAndChildrenById()方法返回递归所有子分类
            categoryIdList = categoryService.selectCategoryAndChildrenById(category.getId()).getData();
        }
        if (StringUtils.isNotBlank(keyword)) {
            keyword = new StringBuilder().append("%").append(keyword).append("%").toString();   //对关键字查询拼装
        }

        /**
         * 关于MyBatis+PageHelper查询结果排序的两种方式
         * ①使用PageHelper排序
         * 方法一：
         *      PageHelper.startPage(pageNum,pageSize);
         *      PageHelper.orderBy("A B");
         *      其中A为排序依据的字段名，B为排序规律，desc为降序，asc为升序
         * 方法二：
         *      String orderBy = "字段名 排序规律"
         *      PageHelper.startPage(pageNum,pageSize.orderBy);
         *
         * ②使用Mybatis排序
         *      XXXExample example = new XXXExample();
         *      example.setOrderBuClause("字段名1 ASC/DESC,字段名2 ASC/DESC,...")；
         *
         */
        //todo 价格排序功能还没有实现，回头还要写
        PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotBlank(orderBy)) {
            //为什么使用set集合保存price_asc和price_desc，而不是用list呢，因为set的contains方法的时间复杂度为O(1),list的为O(n),效率大大提高
            if (Constant.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)) {
                String[] orderByArray = orderBy.split("_");
                PageHelper.orderBy(orderByArray[0] + " " + orderByArray[1]); //order desc  order asc
            }
        }

        List<Product> productList = productMapper.selectProductByNameAndCategoryIds(StringUtils.isBlank(keyword) ? null : keyword, categoryIdList.size() == 0 ? null : categoryIdList);
        List<ProductListVO> productListVOList = Lists.newArrayList();
        for (Product productItem : productList) {
            ProductListVO productListVO = assembleProductListVO(productItem);
            productListVOList.add(productListVO);
        }

        //对productList进行分页，并将list对象设置为productListVOList，等同于PageInfo pageInfo = new PageInfo(productListVOList);
        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(productListVOList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * 组装 ProductListVO
     *
     * @param product
     * @return
     */
    private ProductListVO assembleProductListVO(Product product) {
        ProductListVO productListVO = new ProductListVO();
        productListVO.setId(product.getId());
        productListVO.setCategoryId(product.getCategoryId());
        productListVO.setName(product.getName());
        productListVO.setMainImage(product.getMainImage());
        productListVO.setPrice(product.getPrice());
        productListVO.setStatus(product.getStatus());
        productListVO.setSubtitle(product.getSubtitle());
        productListVO.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymmall.com/"));
        return productListVO;
    }


    public ProductDetailVO assembleProductDetailVO(Product product) {

        ProductDetailVO productDetailVO = new ProductDetailVO();
        productDetailVO.setId(product.getId());
        productDetailVO.setSubtitle(product.getSubtitle());
        productDetailVO.setPrice(product.getPrice());
        productDetailVO.setMainImage(product.getMainImage());
        productDetailVO.setSubImages(product.getSubImages());
        productDetailVO.setCategoryId(product.getCategoryId());
        productDetailVO.setDetail(product.getDetail());
        productDetailVO.setName(product.getName());
        productDetailVO.setStatus(product.getStatus());
        productDetailVO.setStock(product.getStock());

        productDetailVO.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymmall.com/"));
        Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
        if (category == null) {
            productDetailVO.setParentCategoryId(0);
        } else {
            productDetailVO.setParentCategoryId(category.getParentId());
        }

        productDetailVO.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));
        productDetailVO.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime()));
        return productDetailVO;
    }

    /**
     * 修改商品销售状态 -- 上下架
     *
     * @param productId
     * @param status
     * @return
     */
    @Override
    public ServerResponse<String> setSaleStatus(Integer productId, Integer status) {
        if (productId == null || status == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product = new Product();
        product.setId(productId);
        product.setStatus(status);
        //更新，注意这里不要调用updateByPrimaryKey，要调用updateByPrimaryKeySelective
        int rowCount = productMapper.updateByPrimaryKeySelective(product);
        if (rowCount > 0) {
            return ServerResponse.createBySuccessMessage("修改商品销售状态成功");
        }
        return ServerResponse.createByErrorMessage("修改商品销售失败");
    }

    /**
     * 商品搜索
     *
     * @param productName
     * @param productId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ServerResponse<PageInfo> searchProduct(String productName, Integer productId, int pageNum, int pageSize) {
        //设置分页数据
        PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotBlank(productName)) {
            /**
             * 模糊查询，注意拼接，查询携带productName的商品 like% 与 %%区别
             *
             * select * from shopping-mall where name like '%productName%'and id = productId
             * %productName%:查询含有productName的数据
             * %productName:查询以productName结尾的数据
             * productName%:查询以productName开头的数据
             */
            productName = new StringBuilder().append("%").append(productName).append("%").toString();
        }
        List<Product> productList = productMapper.selectByProductNameAndProductId(productName, productId);

        List<ProductListVO> productListVOList = Lists.newArrayList();
        for (Product productItem : productList) {
            ProductListVO productListVO = Product2ProductListVOConverter.convert(productItem);
            productListVOList.add(productListVO);
        }
        PageInfo pageResult = new PageInfo(productList);
        pageResult.setList(productListVOList);

        return ServerResponse.createBySuccess(pageResult);
    }

    /**
     * 商品详情
     *
     * @param productId
     * @return
     */
    @Override
    public ServerResponse<ProductDetailVO> manageProductDetail(Integer productId) {
        if (productId == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null) {
            return ServerResponse.createByErrorMessage("商品已下架或者已被删除");
        }
        /**
         * 这里可以通过静态类调用方法，Java静态变量相当于类变量，它开始于类的创建，被static修饰过的都是随着类的初始化后就产生了.
         */
        ProductDetailVO productDetailVO = this.assembleProductDetailVO(product);
        return ServerResponse.createBySuccess(productDetailVO);
    }
}
